package com.app.service.impl;

import com.alibaba.excel.EasyExcel;
import com.app.controller.importExcel.ImportExcelListener;
import com.app.mapper.ProtectionPointMapper;
import com.app.model.*;
import com.app.service.DepartmentService;
import com.app.service.ProtectionPointService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TestFileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.ListUtils;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
@Primary
public class ProtectionPointServiceImpl implements ProtectionPointService {
    @Autowired
    ProtectionPointMapper protectionPointMapper;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public ProtectionPointModel getPointById(int id) {
        QueryWrapper<ProtectionPointModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().eq("id", id);
        ProtectionPointModel protectionPointModel = protectionPointMapper.selectOne(queryWrapper);
        if (protectionPointModel == null) {
            return null;
        } else {
            return protectionPointModel;
        }
    }

    @Override
    public Page<ProtectionPointModel> getPagePointList(Integer page, Integer limit, String name, List<Integer> idList, Integer departmentId, Integer sortType) {
        QueryWrapper<ProtectionPointModel> queryWrapper = new QueryWrapper<>();
        if (idList.size() > 0) {
            for (int i = 0; i < idList.size(); i++) {
                queryWrapper.select().in("department_id", idList);
            }
        } else {
            queryWrapper.select();
        }
        if (name != null) {
            queryWrapper.select().like("name", name);
        }
        if (departmentId != null) {
            queryWrapper.eq("department_id", departmentId);
        }
        if (sortType==null || sortType==1){
            queryWrapper.orderByAsc("number");
        }else {
            queryWrapper.orderByDesc("number");
        }
        Page<ProtectionPointModel> pages = new Page<>();
        pages.setCurrent(page);
        pages.setSize(limit);
        return protectionPointMapper.selectPage(pages, queryWrapper);
    }

    @Override
    public void update(ProtectionPointModel model) {
        protectionPointMapper.updateById(model);
    }

    @Override
    public void insert(ProtectionPointModel model) {
        protectionPointMapper.insert(model);
    }

    @Override
    public void delete(int id) {
        protectionPointMapper.deleteById(id);
    }

    @Override
    public Integer proCount(List<Integer> idsList) {
        QueryWrapper<ProtectionPointModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        if (idsList != null && idsList.size() > 0) {
            queryWrapper.in("department_id", idsList);
        }
        Integer proCount = protectionPointMapper.selectCount(queryWrapper);
        return proCount;
    }

    @Override
    public List<ProtectionPointModel> getStatisticsByIds(List<Integer> idList, String key) {
        QueryWrapper<ProtectionPointModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(key, "COUNT(*) as count");
        if (idList == null && idList.size() <= 0) {
            queryWrapper.select();
        } else {
            for (int i = 0; i < idList.size(); i++) {
                queryWrapper.or().eq("department_id", idList.get(i));
            }
        }
        queryWrapper.groupBy(key);
        List<ProtectionPointModel> personModelList = protectionPointMapper.selectList(queryWrapper);
        return personModelList;
    }

    @Override
    public List<ProtectionPointModel> selectList() {
        return protectionPointMapper.selectList(null);
    }

    @Override
    public List<ProtectionPointModel> getPlantByIds(List<Integer> appIdList) {
        QueryWrapper<ProtectionPointModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().in("id", appIdList);
        List<ProtectionPointModel> personModelList = protectionPointMapper.selectList(queryWrapper);
        return personModelList;
    }

    // 导入保护点.信息导入
    @Override
    public String importProtectionPoint(MultipartFile file) throws IOException {
        List<String> errorList = new ArrayList<>();
        String path = TestFileUtil.getPath() + "excel.xlsx";
        File localFile = new File(path);
        file.transferTo(localFile);
        String filePath = localFile.getAbsolutePath();
        AtomicReference<Integer> row = new AtomicReference<>(new Integer(0));
        try {
            EasyExcel.read(filePath, ProtectionPointModel.class, new ImportExcelListener<ProtectionPointModel>(dataList -> {
                for (ProtectionPointModel protectionPointModel : dataList) {
                    DepartmentModel departmentModel = departmentService.getdepByName(protectionPointModel.getDepartmentName());
                    if (departmentModel != null) {
                        protectionPointModel.setDepartmentId(departmentModel.getId());
                    }
                    protectionPointModel.setCreateTime(CommonHelp.getNowTimestamp());
                    protectionPointMapper.insert(protectionPointModel);
                    row.set(row.get() + 1);
                }
            }, errorList)).sheet().headRowNumber(1).doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return "处理Excel失败";
        }
        localFile.delete();
        if (row.get() == 0) {
            return "导入0条，请检查模版或者数据格式";
        }
        StringBuilder msg = new StringBuilder("成功导入" + row + "行。");
        if (errorList.size() != 0) {
            for (String error : errorList) {
                msg.append(error);
            }
        }
        return msg.toString();
    }

    /**
     * 批量删除保护点信息
     * @param ids
     * @param request
     * @return
     */
    @Override
    public Result<Object> deleteBatchByIds(String ids, HttpServletRequest request) {
        // 参数校验
        if (StringUtils.isEmpty(ids)) {
            return Result.success("参数为空，无需删除");
        }
        List<Integer> idsList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        // 批量删除
        if (!ListUtils.isEmpty(idsList)) {
            protectionPointMapper.deleteBatchIds(idsList);
            return Result.success("批量删除成功");
        } else {
            return Result.success("批量删除失败，数据为空");
        }
    }
}
